<template>
  <div style="padding-top: 40px;">
    <!--用户个人信息-->
    <el-row type="flex" justify="center">
      <el-col :span="14" style="display: flex; flex-direction: column; align-items: center;">
        <!--获取当前用户用户名、性别和手机号-->
        <div style="margin-top: 10px; ">
          <span style="font-weight: bold; font-size: 26px; margin-top: 20px; margin-right: 10px;">{{user.username}}</span>
          <el-icon :style="{fontSize: '20px', fontWeight: 'bold', color: user.gender === '女' ? 'hotpink' : 'dodgerblue'}">
            <component :is="user.gender === '女' ? 'Female' : 'Male'"/>
          </el-icon>
        </div>
        <div style="display: flex; align-items: center; margin: 20px 0;">
          <el-text style="font-size: 16px; margin-right: 30px;">电话号码：{{user.phone}}</el-text>
          <el-text style="font-size: 16px; margin-right: 30px;">积分：{{user.points}}</el-text>
          <el-button @click="editUser(user.id)" class="edit" >编辑资料</el-button>
        </div>
        <!--编辑资料弹窗-->
        <el-dialog
            :title="dialogTitle"
            style="width:400px; height:400px; padding:40px;"
            v-model="dialogVisible"
            :before-close="handleClose"
        >
          <el-form label-position="top" label-width="80">
            <el-form-item label="用户名" label-position="left" style="margin-top: 20px;">
              <el-input v-model="saveUserForm.username" placeholder="请输入用户名"></el-input>
            </el-form-item>
            <el-form-item label="手机号" label-position="left">
              <el-input v-model="saveUserForm.phone" placeholder="请输入手机号"></el-input>
            </el-form-item>
            <el-form-item label="性别" label-position="left">
              <el-radio-group v-model="saveUserForm.gender">
                <el-radio label="男">男</el-radio>
                <el-radio label="女">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>
          <template #footer>
            <el-button type="info" @click="handleClose">取消</el-button>
            <el-button type="success" @click="saveUser" >确认修改</el-button>
          </template>
        </el-dialog>
      </el-col>
    </el-row>
    <hr style="margin-bottom: 20px;">

    <!--垃圾投放记录表-->
    <el-card style="margin: 10px; display: flex; flex-direction: column; min-height: calc(100% - 10vh - 100px);">
      <span style="font-size: 18px;font-weight: bold;color: grey;margin: 30px;">我的投放记录</span>
      <el-button type="success" @click="toPut" style="float: right; margin-right: 30px;">去投放</el-button>
      <hr style="margin-top: 20px;">
      <el-table :data="pagedRecordArr" style="flex: 1;">
        <el-table-column type="index" label="序号" width="80" align="center">
          <template #default="scope">
            {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="name" label="垃圾名称" align="center"></el-table-column>
        <el-table-column prop="category" label="垃圾类别" align="center"></el-table-column>
        <el-table-column prop="createTime" label="投放时间" align="center"></el-table-column>
        <el-table-column prop="num" label="数量（份）" align="center"></el-table-column>
        <el-table-column prop="status" label="状态" align="center" >
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-button type="danger" link @click="deleteRecord(scope.row.id)" style="font-weight: bold;">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <div style="padding: 20px 0; text-align: center;">
        <el-pagination
            layout="prev, pager, next"
            :total="recordArr.length"
            :page-size="pageSize"
            :current-page="currentPage"
            @current-change="handlePageChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import {computed, onMounted, ref} from "vue";
import {ElMessage, ElMessageBox} from "element-plus";
import axios from "axios";
import qs from "qs";

const toPut = () => {
  window.location.href = "/put";
}
//获取当前用户的信息显示在右上角以及个人中心主页
const user = ref(getUser());
//控制弹窗是否出现
const dialogVisible = ref(false);
//维护弹窗标题
const dialogTitle = ref();
//定义对象用来收集用户保存表单的数据
const saveUserForm = ref({
  username:'',
  phone:'',
  gender:''
});

const userUpdate = ()=>{
  axios.get('http://localhost:8080/v1/user/select?id='+user.value.id).then((response)=>{
    if(response.data.code == 2000){
      user.value = response.data.data[0];
    }else{
      ElMessage.error(response.data.msg);
    }
  })
}
onMounted(()=>{
  userUpdate();
})

//定义点击编辑资料按钮时调用的方法:处理编辑资料时弹窗的标题
const editUser = (id)=>{
  dialogTitle.value = '编辑用户';
  dialogVisible.value = true;
  //获取当前待编辑的用户数据,回显在弹窗中
  axios.get('http://localhost:8080/v1/user/select?id='+id).then((response)=>{
    if(response.data.code == 2000){
      //后端返回的数据类型是List<UserVO>,前端以数组类型接收,所以需要data[0]取数组的第一个元素才行
      saveUserForm.value = {
        ...response.data.data[0],
        id: response.data.data[0].id  // 确保id被正确传递
      };
    }else{
      ElMessage.error(response.data.msg);
    }
  })
}

const saveUser = ()=>{
  console.log(saveUserForm.value);
  let data = qs.stringify(saveUserForm.value);
  axios.post('http://localhost:8080/v1/user/save',data)
      .then((response)=>{
        if(response.data.code == 2000){
          ElMessage.success('保存成功!');
          user.value = {
            ...user.value,
            username: saveUserForm.value.username,
            phone: saveUserForm.value.phone,
            gender: saveUserForm.value.gender
          };
          dialogVisible.value = false;
          saveUserForm.value = {};
        }else{
          ElMessage.error(response.data.msg);
        }
      })
}
//定义处理弹窗关闭的方法
const handleClose = () => {
  ElMessageBox.confirm('确认不保存修改吗？', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    center: false,
  }).then(() => {
    saveUserForm.value = {};
    dialogVisible.value = false;
  }).catch(() => {

  })
}

//垃圾投放记录表
//获取垃圾投放记录表数据
const recordArr  = ref([]);
const recordForm = ref({
  name:'',
  category:'',
  img:'',
  num:'',
  userId:user.value.id,
});
//获取垃圾投放记录表数据，但仅显示目前登录用户userId的数据
const loadRecord = () => {
  let data = qs.stringify(recordForm.value);

  axios.get('http://localhost:8080/v1/record/select?'+data).then((response)=>{
    //如果查询记录为空，则提示用户您暂未投放垃圾
    if(response.data.data.length == 0){
      ElMessage.warning('您暂未投放垃圾');
    }
    if(response.data.code == 2000){
      recordArr.value = response.data.data;
      currentPage.value = 1; // 搜索后重置到第一页
    }else{
      ElMessage.error(response.data.msg);
    }
  })

};

onMounted(() => {
  loadRecord();
});

const getStatusText = (statusCode) => {
  switch(statusCode) {
    case 10: return '未审核'
    case 20: return '审核通过'
    case 30: return '审核未通过'
    default: return '未知状态'
  }
}

const getStatusTagType = (statusCode) => {
  switch(statusCode) {
    case 10: return 'warning'
    case 20: return 'success'
    case 30: return 'danger'
    default: return 'info'
  }
}

const deleteRecord = (id) => {
  ElMessageBox.confirm('确定删除该记录吗？', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    center: false,
  }).then(() => {
    axios.post('http://localhost:8080/v1/record/delete/' + id)
        .then((response) => {
          if (response.data.code == 2000) {
            ElMessage.success('删除成功!');
            loadRecord(); // 删除成功后,需要重新加载用户列表数据!
          } else {
            ElMessage.error(response.data.msg);
          }
        })
        .catch((error) => {
          ElMessage.error('删除记录时发生错误');
          console.error(error);
        });
  }).catch(() => {
    // 用户点击取消，不执行任何操作
  });
}

// 分页相关变量
const currentPage = ref(1);
const pageSize = ref(5);
// 计算属性：返回当前页的数据
const pagedRecordArr = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return recordArr.value.slice(start, end);
});
// 处理页码变化
const handlePageChange = (page) => {
  currentPage.value = page;
};
</script>

<style scoped>
.el-link {
  background-color: #666666;
  margin: 5px;
  width: 120px;
  font-size: 17px;
  text-color: #fff;
  active-background-color: #35984b;
  active-text-color: #35984b;
  padding: 5px 0;
  text-align: center;
}

.el-link.active {
  background-color: #35984b;
  color: #fff;
}

.edit {
  width: 70px;
  height: 25px;
  font-size: 14px;
  border-radius: 5px;
  border-color: #666;
  background-color: #666;
  color: #fff;
}

/* 输入框 */
:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #008800 inset !important;
}

/* 单选框 */
:deep(.el-radio__input.is-checked .el-radio__inner) {
  border-color: #008800 !important;
  background-color: #008800 !important;
}
:deep(.el-radio__input.is-checked + .el-radio__label) {
  color: #008800 !important;
}
.el-pagination {
  justify-content: center;}
</style>